export function downloadFile(response) {
    const blobUrl = window.URL.createObjectURL(response.data);

    let contentDisposition = response.headers["content-disposition"], //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
        patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*"),
        result = patt.exec(contentDisposition),
        filename = decodeURI(result?.length > 0 ? result[1] : '');

    const a = document.createElement("a");
    a.download = filename;
    a.href = blobUrl;
    document.body.appendChild(a);
    a.click();
    a.remove();
}

export const classifyList = [
    // {
    //     name: "img_classify",
    //     text: "图像分类"
    // },
    // {
    //     name: "txt_classify",
    //     text: "文本分类"
    // },
    // {
    //     name: "voice_classify",
    //     text: "声音分类"
    // },
    {
        name: "data_predict",
        text: "数据预测"
    },
    // {
    //     name: "img_detection",
    //     text: "物体检测"
    // },
    {
        name: "data_unsupervised",
        text: "无监督学习"
    }
];

export const progressRate = [
    {
        value: "material",
        text: "导入素材"
    },
    {
        value: "train",
        text: "训练模型中"
    },
    {
        value: "publish",
        text: "训练完成"
    },
    {
        value: "published",
        text: "已发布"
    }
];

/**
 * 获取对单个应字段
 * @param {*} val 值
 * @param {*} dict 列表
 * @param {*} idKey keyName键名
 * @param {*} nameKey valueName值名
 * @param {*} flag 空值时是否显示''
 * fetchSingleWord({ val: '1', dict: list, idKey: 'id', nameKey: 'name', flag: false, isNumber: true, split: ','}) // xxx
 */
export const fetchSingleWord = ({ val, dict, idKey, nameKey, flag }) => {
    dict = dict && dict.length ? dict : [];
    idKey = idKey || "id";
    nameKey = nameKey || "name";
    flag = flag || false;
    if (!val && val !== 0 && typeof val !== "boolean") return flag ? flag : "";
    for (let i = 0; i < dict.length; i++) {
        if (val === dict[i][idKey]) {
            return dict[i][nameKey];
        }
    }
};

/**
 * 验证参数是否通过
 * @param {*} form .el-form ref
 * @param {*} m this
 */
export const doSubmit = (form, m) => {
    let rs = true;
    m.$refs[form].validate(valid => {
        if (valid) {
            rs = true;
        } else {
            rs = false;
        }
    });
    if (!rs) {
        m.$message({
            showClose: true,
            message: "请检查必填项是否为空以及输入是否正确！",
            type: "warning"
        });
    }
    return rs;
};

// 重置所有表单
/*
form: 要重置的表单数据 object
limit: 排除的表单数据 array */

export const restData = (form, limit = []) => {
    // 没有传值返回
    if (!form || (!limit && !form)) return;
    // 非数组返回
    if (!(limit instanceof Array)) return;
    // 传入的表单非对象返回
    if (typeof form !== "object") return;
    // 传入数组判断
    if (limit.length) {
        for (let key in form) {
            limit.map(item => {
                if (item === key) {
                    return;
                } else {
                    if (form[key] instanceof Array) {
                        for (let index = 0; index < form[key].length; index++) {
                            const element = form[key][index];
                            for (const key in element) {
                                element[key] = "";
                            }
                        }
                        // form[key] = [];
                    } else if (typeof form[key] === "object") {
                        form[key] = {};
                    } else {
                        form[key] = "";
                    }
                }
            });
        }
    } else {
        for (let key1 in form) {
            if (form[key1] instanceof Array) {
                for (let index = 0; index < form[key1].length; index++) {
                    const element = form[key1][index];
                    for (const key in element) {
                        element[key] = "";
                    }
                }
                // form[key1] = [];
            } else if (typeof form[key1] === "object") {
                if (form[key1] instanceof Date) {
                    form[key1] = "";
                } else {
                    form[key1] = {};
                }
            } else {
                form[key1] = "";
            }
        }
    }
};

export const format = (time, format, nullValue) => {
    if (!time) {
        return nullValue ? nullValue : "";
    }
    const isString = typeof time === "string";
    let t;
    if (isString) {
        t = new Date(time.replace(/-/g, "/"));
    } else {
        t = new Date(time);
    }

    let tf = i => {
        return (i < 10 ? "0" : "") + i;
    };
    return format.replace(/yyyy|MM?|dd?|HH?|mm?|ss?/g, a => {
        switch (a) {
            case "yyyy":
                return tf(t.getFullYear());
            case "MM":
                return tf(t.getMonth() + 1);
            case "mm":
                return tf(t.getMinutes());
            case "dd":
                return tf(t.getDate());
            case "HH":
                return tf(t.getHours());
            case "ss":
                return tf(t.getSeconds());
        }
    });
};

/**
 * 返回比率
 * @param {*} num 除数
 * @param {*} total 被除数
 * @param {*} precision 精确度
 */
export const getRate = (num, total, precision = 2) => {
    if (!num && num !== 0 && !total && total !== 0) return "--";
    if (num === 0) {
        return (0).toFixed(precision) + "%";
    } else if (total === 0) {
        return "-";
    } else {
        return ((num / total) * 100).toFixed(precision) + "%";
    }
};

// 文件流导出txt文件
export const downloadFileNew = (res, fileName = "") => {
    const response = res;
    const tempNameStr = response.headers["content-disposition"].split(";")[1];
    fileName = fileName || tempNameStr.split("=")[1];
    const blob = new Blob([response.data]);
    const objectUrl = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = objectUrl;
    link.download = fileName;
    link.click();
    link.remove();
};

/**
 * 文件大小,最大TB
 * @param {*} size 单位B
 * @param {*} precision 精确度
 */
export const formatFileSize = (size, precision = 2) => {
    const KB = 1024;
    const MB = 1024 * 1024;
    const GB = 1024 * 1024 * 1024;
    const TB = 1024 * 1024 * 1024 * 1024;
    if (!size && size !== 0) return "--";
    if (size < KB) return `${size}B`;
    if (size < MB) {
        if (size % KB === 0) return `${size / KB}K`;
        return `${(size / KB).toFixed(precision)}K`;
    }
    if (size < GB) {
        if (size % MB === 0) return `${size / MB}MB`;
        return `${(size / MB).toFixed(precision)}MB`;
    }
    if (size < TB) {
        if (size % GB === 0) return `${size / GB}GB`;
        return `${(size / GB).toFixed(precision)}GB`;
    }
    if (size % TB === 0) return `${size / TB}TB`;
    return `${(size / TB).toFixed(precision)}TB`;
};

// 处理文字，显示指定长度，多余的字按...省略显示,默认20个字
export const cutText = (text, length = 20) => {
    if (!text) return "";
    if (text.length <= length) {
        return text;
    } else {
        return text.slice(0, length) + "...";
    }
};
